﻿using System;
using System.Web.DynamicData;
using System.Web.UI.WebControls;

namespace PD.Web.DynamicData.PageTemplates
{
    /// <summary>
    /// Edit entity page.
    /// </summary>
    public partial class Edit : System.Web.UI.Page
    {
        /// <summary>
        /// The metadata that describes a table for use by Dynamic Data pages.
        /// </summary>
        private MetaTable table;

        /// <summary>
        /// Gets the table.
        /// </summary>
        public MetaTable Table
        {
            get { return this.table; }
        }

        /// <summary>
        /// Handles the Init event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Init(object sender, EventArgs e)
        {
            this.table = DynamicDataRouteHandler.GetRequestMetaTable(this.Context);
            this.FormView1.SetMetaTable(this.table);
            this.DetailsDataSource.EntityTypeName = this.table.EntityType.AssemblyQualifiedName;
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = this.table.DisplayName;
        }

        /// <summary>
        /// Handles the ItemCommand event of the FormView1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.FormViewCommandEventArgs"/> instance containing the event data.</param>
        protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            if (e.CommandName == DataControlCommands.CancelCommandName)
            {
                this.Response.Redirect(this.table.ListActionPath);
            }
        }

        /// <summary>
        /// Handles the ItemUpdated event of the FormView1 control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.FormViewUpdatedEventArgs"/> instance containing the event data.</param>
        protected void FormView1_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
        {
            if (e.Exception == null || e.ExceptionHandled)
            {
                this.Response.Redirect(this.table.ListActionPath);
            }
        }
    }
}
